﻿using UnityEngine;
using UnityEditor;

public class AnimationOptimizerTool : EditorWindow
{
    [MenuItem("Tools/Optimize Animations")]
    public static void ShowWindow()
    {
        GetWindow<AnimationOptimizerTool>("Animation Optimizer");
    }

    private void OnGUI()
    {
        GUILayout.Label("Optimize All Animation Clips in the Project", EditorStyles.boldLabel);

        if (GUILayout.Button("Optimize Animations"))
        {
            OptimizeAllAnimations();
        }
    }

    private void OptimizeAllAnimations()
    {
        string[] guids = AssetDatabase.FindAssets("t:AnimationClip");

        foreach (string guid in guids)
        {
            string assetPath = AssetDatabase.GUIDToAssetPath(guid);
            AnimationClip clip = AssetDatabase.LoadAssetAtPath<AnimationClip>(assetPath);

            if (clip != null)
            {
                OptimizeAnimationClip(clip);
            }
        }

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        Debug.Log("All animations have been optimized.");
    }

    private void OptimizeAnimationClip(AnimationClip clip)
    {
        // 减少关键帧数量
        clip.legacy = true; // 使用旧版动画系统，减少内存占用
        clip.wrapMode = WrapMode.Loop; // 设置循环模式，减少内存占用

        // 压缩动画数据
        clip.legacy = false; // 切换回新版动画系统
        clip.ClearCurves(); // 清除不必要的曲线数据

        // 设置动画剪辑的帧率
        clip.frameRate = 15; // 降低帧率，减少内存占用

        Debug.Log($"Optimized animation clip: {clip.name}");
    }
}
